<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="900">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="135px"
      v-loading="formLoading"
    >
      <el-form-item label="商品分类" prop="categoryId">
        <el-tree-select
          v-model="formData.categoryId"
          :data="categoryTree"
          :props="{ ...defaultProps, label: 'categoryName' }"
          check-strictly
          default-expand-all
          placeholder="请选择"
        />
      </el-form-item>
      <el-form-item label="商品品牌" prop="brandId">
        <el-select v-model="formData.brandId" placeholder="请选择">
          <el-option
            v-for="brand in brandOptions"
            :key="brand.id"
            :label="brand.brandName"
            :value="brand.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入商品名称" />
      </el-form-item>
      <el-form-item label="商品封面图" prop="picUrl">
        <UploadImg v-model="formData.picUrl" />
      </el-form-item>
      <el-form-item label="商品状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_SPU_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="最高回收价/分" prop="highestPrice">
        <el-input v-model="formData.highestPrice" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="最低回收价/分" prop="lowestPrice">
        <el-input v-model="formData.lowestPrice" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="市场价/分" prop="marketPrice">
        <el-input v-model="formData.marketPrice" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="赠送积分" prop="giveIntegral">
        <el-input v-model="formData.giveIntegral" placeholder="请输入赠送积分" />
      </el-form-item>
      <el-form-item label="分销的佣金/分" prop="firstBrokeragePrice">
        <el-input v-model="formData.firstBrokeragePrice" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { ReProductSpuApi, ReProductSpu } from '@/api/recycling/recyproductspu'
import { CategoryApi, Category } from '@/api/recycling/category'
import { defaultProps, handleTree } from '@/utils/tree'
import { BrandApi, Brand } from '@/api/recycling/brand'

/** 回收商品spu 表单 */
defineOptions({ name: 'ReProductSpuForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const categoryTree = ref() // 树形结构
const brandOptions = ref()

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  name: undefined,
  categoryId: undefined,
  brandId: undefined,
  picUrl: undefined,
  status: undefined,
  highestPrice: undefined,
  lowestPrice: undefined,
  marketPrice: undefined,
  giveIntegral: undefined,
  firstBrokeragePrice: undefined,
  sort: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
  categoryId: [{ required: true, message: '商品分类不能为空', trigger: 'blur' }],
  picUrl: [{ required: true, message: '商品封面图不能为空', trigger: 'blur' }],
  status: [
    {
      required: true,
      message: '商品状态',
      trigger: 'change'
    }
  ],
  highestPrice: [{ required: true, message: '最高回收价不能为空', trigger: 'blur' }],
  lowestPrice: [{ required: true, message: '最低回收价不能为空', trigger: 'blur' }],
  giveIntegral: [{ required: true, message: '赠送积分不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  brandOptions.value = (await BrandApi.getBrandPage({ pageNo: 1, pageSize: 99, status: 1 })).list

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ReProductSpuApi.getReProductSpu(id)
    } finally {
      formLoading.value = false
    }
  }
  await getCategoryTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ReProductSpu
    if (formType.value === 'create') {
      await ReProductSpuApi.createReProductSpu(data)
      message.success(t('common.createSuccess'))
    } else {
      await ReProductSpuApi.updateReProductSpu(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    name: undefined,
    categoryId: undefined,
    brandId: undefined,
    picUrl: undefined,
    status: undefined,
    highestPrice: undefined,
    lowestPrice: undefined,
    marketPrice: undefined,
    giveIntegral: undefined,
    firstBrokeragePrice: undefined,
    sort: undefined
  }
  formRef.value?.resetFields()
}
/** 获得回收品类树 */
const getCategoryTree = async () => {
  categoryTree.value = []
  const data = await CategoryApi.getCategoryList()
  const root: Tree = { id: 0, name: '顶级回收品类', children: [] }
  root.children = handleTree(data, 'id', 'parentId')
  categoryTree.value.push(root)
}
</script>
